<?php

/**
 * Created by PhpStorm.
 * User: dung
 * Date: 11/11/14
 * Time: 10:46 AM
 */
use Carbon\Carbon;

class Question extends Eloquent
{

    use SoftDeletingTrait;

    public $timestamps = true;
    protected $dates = ['deleted_at'];

    public function topics()
    {
        return $this->belongsToMany('Topic', 'topicables', 'question_id', 'topic_id');
    }

    public function tags()
    {
        return $this->belongsToMany('Tag', 'taggable', 'question_id', 'tag_id');
    }

    public function category()
    {
        return $this->belongsTo('category', 'category_id');
    }

    public function answers()
    {
        return $this->hasMany('Answer', 'Question_id');
    }

    public function user()
    {
        return $this->belongsTo('User', 'user_id');
    }

    public function formattedCreatedDate()
    {
        if ($this->created_at->diffInDays() > 30) {
            $result = str_replace('yearhs', 'năm', $this->created_at->toFormattedDateString());
            $result = str_replace('yearh', 'năm', $result);
            $result = str_replace('month', 'tháng', $result);
            $result = str_replace('months', 'tháng', $result);
            $result = str_replace('days', 'ngày', $result);
            $result = str_replace('day', 'ngày', $result);
            $result = str_replace('hours', 'giờ', $this->created_at->diffForHumans());
            $result = str_replace('hour', 'giờ', $this->created_at->diffForHumans());
            $result = str_replace('ago', 'trước', $result);
            return $result;
        } else {
            $result = str_replace('days', 'ngày', $this->created_at->diffForHumans());
            $result = str_replace('day', 'ngày', $result);
            $result = str_replace('hours', 'giờ', $result);
            $result = str_replace('hour', 'giờ', $result);
            $result = str_replace('ago', 'trước', $result);
            return $result;
        }
    }

    public function getUpdatedAtAttribute($value)
    {
        return Carbon::parse($value)->format('d/m/Y');
    }

    public function votes()
    {
        return $this->belongsToMany('User', 'votes', 'question_id', 'user_id');
    }

    public function generate_link()
    {
        return route('chi-tiet-hoi-dap', array('id' => $this->id, 'slug' => Str::slug($this->title)));
    }

}
